package com.kfm.src.Demo0925;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Affair {
    public static void main(String[] args) {
        System.out.println(transfer("老兵", "新兵", 2.5));

    }
    public static boolean transfer(String out,String in, double m)
    {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        String url = "jdbc:mysql://localhost:3306/bank";
        String user = "root";
        String pass = "";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, pass);
            connection.setAutoCommit(false);
            String sql = "update customer set money = money-? where name=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1,m);
            preparedStatement.setObject(2,out);
            preparedStatement.execute();
            PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
            preparedStatement1.setObject(1,-m);
            preparedStatement1.setObject(2,in);
            preparedStatement1.execute();

            connection.commit();


        } catch (SQLException e) {
            try {
                System.out.println("执行回滚");
                connection.rollback();
                return false;
            } catch (SQLException ex) {
                System.out.println("回滚异常");
                return false;
            }
        }
        try {
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
